<?php

namespace common\logics\article;

use Yii;

/**
 * S页资讯
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class RssArticleLogic extends BaseArticleLogic {

    /**
     * @return array
     */
    public function getRemoveCategoryIds() {
        return [
            340, 339, 342, 353, 354, 355, 357, 364, 366, 367, 368, 369, 370, 375, 377, 381, 384, 385, 386, 387, 388, 389, 390,
        ];
    }

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find()->alias($alias)->with('category');
        if ($alias) {
            $alias .= '.';
        }
        $query->andWhere([
            $alias . 'deleted_at' => null,
        ]);

        if (!$this->isStaff) {
            $query->innerJoinWith([
                'unionModels' => function ($q) {
                    /* @var $q \yii\db\ActiveQuery */
                    $q->alias('unionModels')->andWhere([
                        'unionModels.model' => 'post'
                    ])->andWhere([
                        'unionModels.root_id' => 0,
                    ]);
                }
            ]);
            $query->orderBy([
                $alias . 'id' => 'DESC'
            ]);
            return $query;
        }

        //移除特定栏目资讯
        $query->andFilterWhere([
            'not in', $alias . 'category_id', $this->getRemoveCategoryIds()
        ]);

        $rootId = $this->getRootId();
        $companyId = $this->getCompanyId();
        $unionId = $this->getUnionId();

        //限制基础资讯权限
        $query->innerJoinWith([
            'unionModels' => function ($q) use($rootId, $companyId) {
                /* @var $q \yii\db\ActiveQuery */
                $q->alias('unionModels')->andWhere([
                    'unionModels.model' => 'post'
                ])->andWhere([
                    'or',
                    [
                        'and',
                        ['unionModels.company_id' => $companyId],
                        ['unionModels.root_id' => $rootId],
                    ],
                    ['unionModels.root_id' => 0],
                ]);
            }
        ]);

        $query->andWhere([
            $alias . 'root_id' => [
                $rootId, 0
            ],
            $alias . 'union_id' => [
                $unionId, 0
            ]
        ]);
        $query->orderBy([
            $alias . 'public_at' => SORT_DESC,
        ]);
        $query->cache(60);
        return $query;
    }

}
